﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Xml;
using WIQA.WeChatAPI.Core;
using System.Linq;
using WIQA.Common.Core;
using WIQA.Bussiness.Entity;
using System.Reflection;

namespace WIQA.Web
{
    public class MessageHandler : IHttpHandler
    {
        /// <summary>
        /// 您将需要在网站的 Web.config 文件中配置此处理程序 
        /// 并向 IIS 注册它，然后才能使用它。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // 如果无法为其他请求重用托管处理程序，则返回 false。
            // 如果按请求保留某些状态信息，则通常这将为 false。
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            XmlDocument xml = new XmlDocument();
            if (context.Request.HttpMethod.ToLower() == "POST")
            {
                //
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(context.Request.InputStream);
                if (xmlDoc.HasChildNodes)
                {
                    byte[] byts = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(byts, 0, byts.Length);
                    string reqXml = System.Text.Encoding.Default.GetString(byts);

                    var obj = XmlHelper.DeSerializeObject<BaseMessage>(reqXml);

                    if (obj == null)
                    {
                        //
                    }

                    var reponseTxt = new ResponseText(new BaseMessage()
                    {
                        FromUserName = "GBTONE",
                        ToUserName = obj.FromUserName
                    });
                    reponseTxt.Content = "Welcome to 程序猿的hellowold,this is test for jerry.";
                    
                    context.Response.Write(reponseTxt.ToXml());

                    LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, reponseTxt.ToXml());

                    context.Response.End();

                }
            }
            else
            {
                Authenticate(context);
            }
        }

        private void Execute()
        {
        }

        private static void Authenticate(HttpContext context)
        {
            var echoStr = context.Request["echoStr"];
            var signature = context.Request["signature"];
            var timestamp = context.Request["timestamp"];
            var nonce = context.Request["nonce"];
            string token = ConfigurationManager.AppSettings["WIQAToken"];
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException("token is null");
            }

            if (new BasicApi().checkSignature(token, signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    context.Response.Write(echoStr);
                    context.Response.End();
                }
            }

            else
            {
                context.Response.Write("<h1>This is for test<h1/>");
            }
        }

        #endregion
    }
}
